package network_programming.np1_socket_and_serversocket;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/** 服务端程序 */
public class ServerDemo {
    private int port = 8000;
    private ServerSocket serverSocket;
    public ServerDemo() throws IOException {
        serverSocket = new ServerSocket(port, 3);
        System.out.println("服务器启动");
    }
    public void service() {
        while(true) {
            Socket socket = null;
            try {
                socket = serverSocket.accept();
                System.out.println("New connection accepted " + socket.getInetAddress() + ":" + socket.getPort());
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if(socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        ServerDemo server = new ServerDemo();
        Thread.sleep(60000);
        server.service();
    }
}
